#include "bsp_nvs.h"
#include "nvs_flash.h"
#include "nvs.h"

#define NVS_CUSTOM_INFO             "CUSTOM_INFO"          // 自定义数据 命名区域

#define NVS_CUSTOM_MQTT_INFO        "MQTT_INFO"          // 在 "自定义数据" 区域下 MQTT信息键值对
#define NVS_CUSTOM_DEVICE_ID_BUFFER "DEVICE_BUFFER"     // 在 "自定义数据" 区域下 设备号数组键值对
#define NVS_CUSTOM_DEVICE_ID_FLAG   "DEVICE_FLAG"       // 在 "自定义数据" 区域下 设备号标志键值对
nvs_info_t nvs_info = {0};

nvs_info_t *get_nvs_info()
{
    return &nvs_info;
}



void save_mqtt_nvs_custom()
{
    nvs_handle_t my_handle;
    nvs_open(NVS_CUSTOM_INFO, NVS_READWRITE, &my_handle);
    nvs_set_str(my_handle, NVS_CUSTOM_MQTT_INFO, nvs_info.mqtt_url);
    nvs_commit(my_handle);
    nvs_close(my_handle);
}

void save_device_id_nvs_custom()
{
    nvs_handle_t my_handle;
    nvs_open(NVS_CUSTOM_INFO, NVS_READWRITE, &my_handle);
    nvs_set_str(my_handle, NVS_CUSTOM_DEVICE_ID_BUFFER, nvs_info.device_id);
    nvs_set_u8(my_handle, NVS_CUSTOM_DEVICE_ID_FLAG, DEVICE_ID_SET_FLAG);
    nvs_commit(my_handle);
    nvs_close(my_handle);
}



void local_nvs_init()
{
    esp_err_t ret;
    size_t read_length = 0;
    nvs_handle_t my_handle;
    // Initialize NVS
    ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK( ret );
    /* 打开自定义数据 区域 */
    ret = nvs_open(NVS_CUSTOM_INFO, NVS_READWRITE, &my_handle);
    if (ret != ESP_OK) {
        printf("Error (%s) opening NVS handle!\n", esp_err_to_name(ret));
    } else {
        /* 找到自定义区域 并成功打开 */
        printf("Done\n");
        /* 读取mqtt信息 */
        ret = nvs_get_str(my_handle, NVS_CUSTOM_MQTT_INFO, NULL, &read_length);
        if(ret != ESP_OK && ret != ESP_ERR_NVS_NOT_FOUND){
            printf("read_mqtt_ERROR!!!\n");
        } 
        if(read_length > 0){
            nvs_get_str(my_handle, NVS_CUSTOM_MQTT_INFO, nvs_info.mqtt_url, &read_length);
            printf("mqtt_read_char = %s\n", nvs_info.mqtt_url);
        }else{
            printf("no mqtt data now!!!\n");
        }
         /* 读取device_id字符串信息 */
        ret = nvs_get_str(my_handle, NVS_CUSTOM_DEVICE_ID_BUFFER, NULL, &read_length);
        if(ret != ESP_OK && ret != ESP_ERR_NVS_NOT_FOUND){
            printf("read_device_ERROR!!!\n");
        } 
        if(read_length > 0){
            nvs_get_str(my_handle, NVS_CUSTOM_DEVICE_ID_BUFFER, nvs_info.device_id, &read_length);
            printf("device_read_char = %s\n", nvs_info.device_id);
        }else{
            printf("no device data now!!!\n");
        }
        /* 读取device_id标志位信息 */
        nvs_get_u8(my_handle, NVS_CUSTOM_DEVICE_ID_FLAG, &nvs_info.device_id_flag);



    }


}










